package com.adjaisd.scarecrow.service.impl;

import com.adjaisd.scarecrow.common.config.OssConfig;
import com.adjaisd.scarecrow.entity.OssToken;
import com.adjaisd.scarecrow.service.OssTokenService;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OssTokenServiceImpl implements OssTokenService {

    @Autowired
    private OssConfig ossConfig;

    @Override
    public OssToken getToken() {
        String region = ossConfig.getRegion();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        String roleArn = ossConfig.getRoleArn();
        String roleSessionName = ossConfig.getRoleSessionName();
        String policy = "{\n" +
                "    \"Version\": \"1\",\n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Effect\": \"Allow\",\n" +
                "            \"Action\": \"oss:*\",\n" +
                "            \"Resource\": [\n" +
                "                \"acs:oss:*:*:sc-avatar\",\n" +
                "                \"acs:oss:*:*:sc-avatar/**\"\n" +
                "            ]\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        try {
            // 添加endpoint（直接使用STS endpoint，前两个参数留空，无需添加region ID）
            DefaultProfile.addEndpoint("", "", "Sts", endpoint);
            // 构造default profile（参数留空，无需添加region ID）
            IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
            // 用profile构造client
            DefaultAcsClient client = new DefaultAcsClient(profile);
            AssumeRoleRequest request = new AssumeRoleRequest();
            request.setMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy); // Optional
            request.setProtocol(ProtocolType.HTTPS); // 必须使用HTTPS协议访问STS服务);
            request.setDurationSeconds(60 * 30L);
            final AssumeRoleResponse response = client.getAcsResponse(request);
            AssumeRoleResponse.Credentials credentials = response.getCredentials();
            return new OssToken(region, ossConfig.getBucket(),
                    credentials.getAccessKeyId(), credentials.getAccessKeySecret(),
                    credentials.getSecurityToken(), credentials.getExpiration());
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
    }
}
